package com.tanhua.dubbo.api;

import com.tanhua.dubbo.utils.IdService;
<<<<<<< HEAD
import com.tanhua.mongo.Album;
import com.tanhua.mongo.Friend;
import com.tanhua.mongo.Publish;
import com.tanhua.mongo.TimeLine;
=======
import com.tanhua.mongo.*;
import com.tanhua.vo.MomentVo;
>>>>>>> acc7004 (第4天到第8天)
import com.tanhua.vo.PageResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;
import java.util.stream.Collectors;

<<<<<<< HEAD

/**
 * @version 1.0
 * @author： xtr
 * @date： 2021-03-10 20:56
=======
/**
 * @version 1.0
 * @author： xtr
 * @date： 2021-03-13 19:36
>>>>>>> acc7004 (第4天到第8天)
 */
@Service
@Slf4j
public class PublishApiImpl implements PublishApi {
<<<<<<< HEAD
=======

>>>>>>> acc7004 (第4天到第8天)
    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IdService idService;

    /**
     * 发布动态
     *
     * @param publish
     */
    @Override
    public void add(Publish publish) {
<<<<<<< HEAD
        //  =======动态表==========
        //统一发布时间
        long timeMillis = System.currentTimeMillis();
        //填充数据，publish的Object id
        ObjectId publishId = ObjectId.get();
        log.info("publishId:{},userId:{}",publishId,publish.getUserId());
        publish.setId(publishId);
        //给推荐系统使用
        publish.setPid(idService.nextId("quanzi_publish"));
        publish.setSeeType(1);//1:公开
        publish.setCreated(timeMillis);
        publish.setState(1);//审核通过
        mongoTemplate.insert(publish);

        //=========操作相册表============
        Album album = new Album();
        album.setId(ObjectId.get());
        album.setCreated(timeMillis);
        album.setPublishId(publishId);
        mongoTemplate.insert(album,"quanzi_album_"+publish.getUserId());

        //===============好有时间表===============
        //查询好友表获取id集合

        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(publish.getUserId()));
        List<Friend> friends = mongoTemplate.find(query, Friend.class);
        if (friends!=null){
            //遍历集合，创建好友时间线表，指定集合(表)名称，每人一张
            for (Friend friend : friends) {
                String collectionName = "quanzi_time_line_"+friend.getFriendId();
                TimeLine timeLine = new TimeLine();
                timeLine.setId(ObjectId.get());
                timeLine.setUserId(friend.getUserId());
                timeLine.setCreated(timeMillis);
                timeLine.setPublishId(publishId);
=======
        // 统一时间
        long timeMillis = System.currentTimeMillis();
        // ================ 动态表 publish ==================
        //4. 填充数据, 生成ObjectId, publish的id
        ObjectId publishId = ObjectId.get();
        log.info("publishId={}, userId={}",publishId, publish.getUserId());
        publish.setId(publishId);
        // 给推荐系统使用的，不理
        publish.setPid(idService.nextId("quanzi_publish"));
        publish.setSeeType(1); //1:公开
        publish.setCreated(timeMillis);
        publish.setState(1); //1：审核通过
        mongoTemplate.insert(publish);

        // ================== 我的相册 =====================
        //6. 构建相册对象，且填充值
        Album album = new Album();
        album.setId(ObjectId.get());
        album.setPublishId(publishId);
        album.setCreated(timeMillis);
        //保存相册,指定集合名称 每人一张表
        mongoTemplate.insert(album,"quanzi_album_" + publish.getUserId());

        // ============= 好友时间线表 ========================
        // 查询好友的id集合
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(publish.getUserId()));
        List<Friend> friends = mongoTemplate.find(query, Friend.class);
        if(null != friends) {
            //9. 遍历好友，添加好友的时间线(构建timeline对象),指定集合名称 每人一张表
            // 【注意】day11 rocketMq 来实现
            for (Friend friend : friends) {
                // 好友的时间线表名
                String collectionName = "quanzi_time_line_" + friend.getFriendId();
                // 构建时间线对象
                TimeLine timeLine = new TimeLine();
                timeLine.setId(ObjectId.get());
                // 创建的时间，
                timeLine.setCreated(timeMillis);
                // 动态的id
                timeLine.setPublishId(publishId);
                // 我是他的好友
                timeLine.setUserId(publish.getUserId());
>>>>>>> acc7004 (第4天到第8天)
                mongoTemplate.insert(timeLine,collectionName);
            }
        }
    }

    /**
<<<<<<< HEAD
     * 查询好友动态
=======
     * 通过用户ID分页查看好友动态
>>>>>>> acc7004 (第4天到第8天)
     *
     * @param page
     * @param pagesize
     * @param userId
     * @return
     */
    @Override
<<<<<<< HEAD
    public PageResult queryFriendPublishList(Long page, Long pagesize, Long userId) {
        //构建时间线表名称
=======
    public PageResult findFriendPublish(Long page, Long pagesize, Long userId) {
>>>>>>> acc7004 (第4天到第8天)
        String collectionName = "quanzi_time_line_"+userId;
        Query query = new Query();
        Long total = mongoTemplate.count(query, collectionName);
        PageResult pageResult = new PageResult();
<<<<<<< HEAD
        pageResult.setPage(page);
        pageResult.setPagesize(pagesize);
        //总页面
        long pages = total/pagesize;
        pages +=total.intValue()%pagesize>0?1:0;
        pageResult.setPages(pages);
        pageResult.setCounts(total);
        //分页查询
        if (total>0){
            //按时间降序分页查询
            query.with(Sort.by(Sort.Order.desc("created"))).with(PageRequest.of(page.intValue()-1,pagesize.intValue()));
            List<TimeLine> timeLines = mongoTemplate.find(query, TimeLine.class, collectionName);
            //获取动态id集合，将集合timeLines中的每个id取出
            List<ObjectId> publishIds = timeLines.stream().map(TimeLine::getPublishId).collect(Collectors.toList());
            //通过动态id查询动态信息
=======
        pageResult.setCounts(total);
        pageResult.setPage(page);
        pageResult.setPagesize(pagesize);
        Long pages = total/pagesize;
        pages += total.intValue()%pagesize>0?1:0;
        pageResult.setPages(pages);
        if (total>0){
            //按创建时间查询并分页
            query.with(Sort.by(Sort.Order.desc("created"))).with(PageRequest.of(page.intValue()-1,pagesize.intValue()));
            List<TimeLine> timeLines = mongoTemplate.find(query, TimeLine.class, collectionName);
            List<ObjectId> publishIds = timeLines.stream().map(TimeLine::getPublishId).collect(Collectors.toList());
            //通过动态id查询动态信息
            Query publishQuery = new Query(Criteria.where("_id").in(publishIds));
            List<Publish> publishes = mongoTemplate.find(publishQuery, Publish.class);
            pageResult.setItems(publishes);
        }
        return pageResult;
    }

    /**
     * 推荐动态
     * @param page
     * @param pagesize
     * @param userId
     * @return
     */
    @Override
    public PageResult queryRecommendPublishList(Long page, Long pagesize, Long userId) {
        Query query = new Query();
        Long total = mongoTemplate.count(query, RecommendQuanzi.class);
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pagesize);
        pageResult.setCounts(total);
        long pages = total/pagesize;
        pages += total.intValue()%pagesize>0?1:0;
        pageResult.setPages(pages);
        if (total>0){
            query.with(Sort.by(Sort.Order.desc("score"))).with(PageRequest.of(page.intValue()-1,pagesize.intValue()));
            List<RecommendQuanzi> recommendQuanzis = mongoTemplate.find(query, RecommendQuanzi.class);
            List<ObjectId> publishIds = recommendQuanzis.stream().map(RecommendQuanzi::getPublishId).collect(Collectors.toList());
>>>>>>> acc7004 (第4天到第8天)
            Query publishQuery = new Query();
            publishQuery.addCriteria(Criteria.where("_id").in(publishIds));
            List<Publish> publishes = mongoTemplate.find(publishQuery, Publish.class);
            pageResult.setItems(publishes);
        }
        return pageResult;
    }
<<<<<<< HEAD
=======

    /**
     * 我的动态
     *
     * @param page
     * @param pagesize
     * @param userId
     * @return
     */
    @Override
    public PageResult findMyMoment(Long page, Long pagesize, Long userId) {
        Query query = new Query();
        String collectionName = "quanzi_album_" + userId;
        Long total = mongoTemplate.count(query, collectionName);
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pagesize);
        pageResult.setCounts(total);
        long pages = total/pagesize;
        pages += total.intValue()%pagesize>0?1:0;
        pageResult.setPages(pages);
        if (total>0){
            query.with(Sort.by(Sort.Order.desc("created"))).with(PageRequest.of(page.intValue()-1,pagesize.intValue()));
            List<Album> albums = mongoTemplate.find(query, Album.class, collectionName);
            List<ObjectId> publishIds = albums.stream().map(Album::getPublishId).collect(Collectors.toList());
            Query publishQuery = new Query(Criteria.where("_id").in(publishIds));
            List<Publish> publishList = mongoTemplate.find(publishQuery, Publish.class);
            pageResult.setItems(publishList);
        }
        return pageResult;
    }

    /**
     * 查询单条动态
     *
     * @param publishId
     * @return
     */
    @Override
    public Publish findById(String publishId) {
        Publish publish = mongoTemplate.findById(new ObjectId(publishId), Publish.class);
        return publish;
    }
>>>>>>> acc7004 (第4天到第8天)
}
